package com.jake.rabbit.rfc.consumer;

import com.jake.rabbit.rfc.producer.ResponseProducer;
import com.jake.rabbit.util.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static com.jake.rabbit.constant.KeyConstants.*;
import static com.jake.rabbit.constant.QueueConstants.REQUEST_QUEUE;
import static com.jake.rabbit.constant.QueueConstants.RESPONSE_QUEUE;
import static com.jake.rabbit.constant.UrlConstants.SAP_ATTENDANCE_URL;

@Component
@RabbitListener(queues = {REQUEST_QUEUE + 1, REQUEST_QUEUE + 2,
        REQUEST_QUEUE + 3, REQUEST_QUEUE + 4, REQUEST_QUEUE + 5})
@Slf4j
public class RequestConsumer {

    @Autowired
    private ResponseProducer responseProducer;

    @RabbitHandler
    public void listenRequestMap(Map<String, Object> requestMap) {
        Map<String, Object> responseMap = HttpClientUtils.getResponseMap(requestMap, SAP_ATTENDANCE_URL);
        String requestId = (String) requestMap.get(REQUEST_ID);
        int requestQueueNumber = (int) requestMap.get(REQUEST_QUEUE_NUMBER);
        if (responseMap == null) {
            log.warn("responseMap is null");
            responseProducer.sendResponseMap(RESPONSE_QUEUE + requestQueueNumber, new HashMap<>(0));
            return;
        }
        responseMap.put(RESPONSE_ID, requestId);
        responseMap.put(RESPONSE_QUEUE_NUMBER, requestQueueNumber);
        responseProducer.sendResponseMap(RESPONSE_QUEUE + requestQueueNumber, responseMap);
    }

}
